/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package company.beans;

import entities.Company;
import entities.CompanyOrder;
import entities.CompanyProduct;
import facades.CompanyOrderFacade;
import java.io.Serializable;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Named;
import qualifiers.ChosenEntityEvent;
import qualifiers.CreatedEntityEvent;
import qualifiers.LoggedIn;
import qualifiers.PreCreateEntityEvent;

/**
 *
 * @author Alvaro
 */
@Named(value = "tPVBean")
@SessionScoped
public class TPVBean implements Serializable {

    private CompanyProduct chosenCompanyProduct;
    private String merchantName;
    private String merchantCode;
    private Integer merchantTerminal;
    private String merchantOrder;
    private String merchantPassword;
    private String merchantCurrency;
    private String merchantTransactionType;
    private String merchantURL;
    private Integer shaLength;
    private String merchantAmount;
    private String merchantSignature;
    private CompanyOrder companyOrder;
    
    @Inject CompanyOrderFacade companyOrderFacade;
    @Inject
    @LoggedIn
    private Company company;
    @Inject
    @PreCreateEntityEvent
    private Event<CompanyOrder> preCreateCompanyOrderEvent;
    @Inject
    @CreatedEntityEvent
    private Event<CompanyOrder> createdCompanyOrderEvent;
    
    
    public TPVBean() {
        merchantName="THE RECRUITERY SL";
        merchantCode="045734365";
        merchantTerminal=1;
        merchantPassword="EW257UJW3";
        merchantCurrency="978";
        merchantTransactionType="0";
        //merchantURL="http://85.137.238.251:15678/TheRecruitery/confirmedPay.xhtml";
        merchantURL="http://www.therecruitery.com/confirmedPay.xhtml";
        shaLength=20;
    }
    
    public void onChosenCompanyProduct(@Observes @ChosenEntityEvent CompanyProduct companyProduct){
        chosenCompanyProduct=companyProduct;
        Integer amount=getChosenCompanyProduct().getBasePrice().multiply(new BigDecimal(100)).intValueExact();
        merchantAmount=amount.toString();
    }
    
    private String createMerchantSignature(){
       byte bAmount[]   = new byte[merchantAmount.length()];  
       byte bOrder[]    = new byte[merchantOrder.length()];  
       byte bCode[]     = new byte[merchantCode.length()];  
       byte bCurrency[] = new byte[merchantCurrency.length()];
       byte bTransactionType[] = new byte[merchantTransactionType.length()];  
       byte bMerchantURL[] = new byte[merchantURL.length()];  
       byte bPassword[] = new byte[merchantPassword.length()];   
 
        bAmount   = merchantAmount.getBytes();
        bOrder    = merchantOrder.toString().getBytes();
        bCode     = merchantCode.getBytes();
        bCurrency = merchantCurrency.getBytes();
        bTransactionType = merchantTransactionType.getBytes();
        bMerchantURL = merchantURL.getBytes();
        bPassword = merchantPassword.getBytes();
        String merchantSignature = new String();
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA-1");
            sha.update(bAmount);
            sha.update(bOrder);
            sha.update(bCode); 
            sha.update(bCurrency);
            sha.update(bTransactionType);
            sha.update(bMerchantURL);
            byte[] hash = sha.digest(bPassword);
            int h = 0;
            String s = new String();
            for(int i = 0; i < shaLength; i++){         
                h = (int) hash[i];          // Convertir de byte a int
                if(h < 0) h += 256;  // Si son valores negativos, pueden haber problemas de conversi¢n.
                s = Integer.toHexString(h); // Devuelve el valor hexadecimal como un String        
                if (s.length() < 2) merchantSignature = merchantSignature.concat("0"); // A¤ade un 0 si es necesario
                    merchantSignature = merchantSignature.concat(s); // A¤ade la conversi¢n a la cadena ya existente
                }
                merchantSignature=merchantSignature.toUpperCase();
            } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(TPVBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return merchantSignature;
    }
    
    public void createCompanyOrder(){
        companyOrder = new CompanyOrder();
        companyOrder.setCompanyProduct(chosenCompanyProduct);
        companyOrder.setDate(new Date());
        companyOrder.setIsPayed(false);
        companyOrder.setCompany(company);
        companyOrder.setAmount(chosenCompanyProduct.getCurrentPrice());
        preCreateCompanyOrderEvent.fire(companyOrder);
        companyOrderFacade.create(companyOrder);
        createdCompanyOrderEvent.fire(companyOrder);
        merchantOrder=companyOrder.getIdCompanyOrder().toString();
        while(merchantOrder.length()<4){
            merchantOrder="0"+merchantOrder;
        }
        if(company.getCompanyOrderList()==null){
            company.setCompanyOrderList(new ArrayList<CompanyOrder>());
        }
        company.getCompanyOrderList().add(companyOrder);
    }
    public void confirmBuy(){
        createCompanyOrder();
        merchantSignature=createMerchantSignature();
    }

    /**
     * @return the chosenCompanyProduct
     */
    public CompanyProduct getChosenCompanyProduct() {
        return chosenCompanyProduct;
    }

    /**
     * @param chosenCompanyProduct the chosenCompanyProduct to set
     */
    public void setChosenCompanyProduct(CompanyProduct chosenCompanyProduct) {
        this.chosenCompanyProduct = chosenCompanyProduct;
    }

    /**
     * @return the merchantName
     */
    public String getMerchantName() {
        return merchantName;
    }

    /**
     * @param merchantName the merchantName to set
     */
    public void setMerchantName(String merchantName) {
        this.merchantName = merchantName;
    }

    /**
     * @return the merchantCode
     */
    public String getMerchantCode() {
        return merchantCode;
    }

    /**
     * @param merchantCode the merchantCode to set
     */
    public void setMerchantCode(String merchantCode) {
        this.merchantCode = merchantCode;
    }

    /**
     * @return the merchantTerminal
     */
    public Integer getMerchantTerminal() {
        return merchantTerminal;
    }

    /**
     * @param merchantTerminal the merchantTerminal to set
     */
    public void setMerchantTerminal(Integer merchantTerminal) {
        this.merchantTerminal = merchantTerminal;
    }

    /**
     * @return the merchantOrder
     */
    public String getMerchantOrder() {
        return merchantOrder;
    }

    /**
     * @param merchantOrder the merchantOrder to set
     */
    public void setMerchantOrder(String merchantOrder) {
        this.merchantOrder = merchantOrder;
    }

    /**
     * @return the merchantPassword
     */
    public String getMerchantPassword() {
        return merchantPassword;
    }

    /**
     * @param merchantPassword the merchantPassword to set
     */
    public void setMerchantPassword(String merchantPassword) {
        this.merchantPassword = merchantPassword;
    }

    /**
     * @return the merchantCurrency
     */
    public String getMerchantCurrency() {
        return merchantCurrency;
    }

    /**
     * @param merchantCurrency the merchantCurrency to set
     */
    public void setMerchantCurrency(String merchantCurrency) {
        this.merchantCurrency = merchantCurrency;
    }

    /**
     * @return the merchantTransactionType
     */
    public String getMerchantTransactionType() {
        return merchantTransactionType;
    }

    /**
     * @param merchantTransactionType the merchantTransactionType to set
     */
    public void setMerchantTransactionType(String merchantTransactionType) {
        this.merchantTransactionType = merchantTransactionType;
    }

    /**
     * @return the merchantURL
     */
    public String getMerchantURL() {
        return merchantURL;
    }

    /**
     * @param merchantURL
     */
    public void setMerchantURL(String merchantURL) {
        this.merchantURL = merchantURL;
    }

    /**
     * @return the shaLength
     */
    public Integer getShaLength() {
        return shaLength;
    }

    /**
     * @param shaLength the shaLength to set
     */
    public void setShaLength(Integer shaLength) {
        this.shaLength = shaLength;
    }

    /**
     * @return the amount
     */
    public String getAmount() {
        return merchantAmount;
    }

    /**
     * @param amount the amount to set
     */
    public void setMerchantAmount(String amount) {
        this.merchantAmount = amount;
    }

    /**
     * @return the merchantSignature
     */
    public String getMerchantSignature() {
        return merchantSignature;
    }

    /**
     * @param merchantSignature the merchantSignature to set
     */
    public void setMerchantSignature(String merchantSignature) {
        this.merchantSignature = merchantSignature;
    }

    /**
     * @return the companyOrder
     */
    public CompanyOrder getCompanyOrder() {
        return companyOrder;
    }

    /**
     * @param companyOrder the companyOrder to set
     */
    public void setCompanyOrder(CompanyOrder companyOrder) {
        this.companyOrder = companyOrder;
    }

    
}
